#!/bin/sh

function fastboot-tflash() {
function fastboot-tflash-help() {
	local cmd=$1
	local rst=$2
	local fl=$3
    if [ $rst -eq 1 ]; then
		echo "$cmd : skip [$fl]"
		return 0
	fi
cat <<EOF
$cmd: try fastboot flash \$file into \$partition
arg1: partition burned
arg2: image to burn
---
e.g. :
    $1 system system.img
    $1 vbmeta vbmeta.img --disable-verification 
EOF
}
	local pt=$1
	local fl=$2
	local arg=$3
    #echo [$pt] [$fl] [$arg] ; return
	if [ ! -f "$fl" ]; then
		fastboot-tflash-help $0 1 $fl; return 1
	fi
	if [ -z "$pt" ]; then
		fastboot-tflash-help $0 0; return 1
	fi
	if [ ! -z "$arg" ]; then
        echo "Burn [$fl] to [$pt], [$arg]"
    else
        echo "Burn [$fl] to [$pt]"
	fi
    fastboot flash $arg  $pt $fl
}

function fastboot-tflashs ()
{
function fastboot-tflashs-help ()
{
cat <<EOF
$1 : try run 'fastboot flash' with file list
arg1: dir,  where image files location
arg2: burn action list about args
---
e.g. :
    cat flash-list-for-6115
    ---
    abl abl.elf
    vbmeta vbmeta.img  --disable-verification 
    ---
    
    $1 out/target/product/bengal flash-list-for-6115
EOF
}
    local hr=`pwd`
    local towhere=$1
    local filelist=$2
	if [ ! -d "$towhere" ]; then
		towhere=`pwd`
	fi
	if [ ! -f "$filelist" ]; then
        echo $filelist
		fastboot-tflashs-help $0; return 1
	fi


cat <<EOF
Type 'a/f' to start burning
"w : Wait second(s), then try until ADB ok."
"A : Try until ADB ok, then exec Fastboot"
"F :  Exec fastboot"
EOF
read answer

case $answer in
    w| W)
        timerout=20
        echo "Wait $timerout second(s)"
        sleep $timerout

        ;&
    a| A)
		echo "alawys wait"
		while true
        do
            adb reboot bootloader > /dev/null  2>&1
            ret=$?
            if [ $ret -eq 0 ]; then
				break
			fi
            sleep 1
        done
        ;&
    f|F)
        echo "fastboot ..."
        cd $towhere
		cat $filelist | while read line
		do
            if [ -z "$line" ]; then
				continue
			fi
            rsult=`echo $line| grep '#'`
            if [ ! -z "$rsult" ]; then
				continue
			fi
            fastboot-tflash $line
		done
        fastboot reboot
        cd $hr
        ;;
    *)
        return ;
        ;;
esac

cat <<EOF
Done...

You Can do it again

EOF
    fastboot-tflashs $@
}

function fastboot-tflashs-demo-filelist ()
{
cat <<EOF
#kernel之前的验证
xbl xbl.elf
xbl_config xbl_config.elf

abl abl.elf

# 防止系统不断重启
vbmeta vbmeta.img  --disable-verification 

# 设备树、内核驱动验证
dtbo  dtbo.img
boot  boot.img

# FCT配置
cache  cache.img

# 安卓系统有关
userdata  userdata.img

# 相当于 vendor 分区 和 system 分区 都包括在内
super  super.img
# vendor vendor.img 
# system  system.img

persist persist.img

recovery recovery.img

metadata metadata.img
EOF
}

